package com.cyb.beta.controller;

import com.cyb.beta.model.MenuResc;
import com.cyb.beta.service.MenuRescService;
import com.cyb.beta.utils.DateUtils;
import com.jfinal.ext.route.ControllerBind;

import java.util.List;

/**
 * Created by Administrator on 2015/6/18.
 */
@ControllerBind(controllerKey = "/admin/menuresc", viewPath = "admin/system")
public class MenuRescController extends BaseController {

    private MenuRescService menuRescService = new MenuRescService();

    public void index() {
        setAttr("rescList", menuRescService.getSortMenuRescList());
        render("menurescList.html");
    }

    /**
     * 查看资源
     */
    public void view() {
        Integer id = getParaToInt(MenuResc.ID);

        setAttr("menuResc", null != id ? MenuResc.dao.find(id) : "");
        render("menurescForm.html");
    }

    /**
     * 修改或保存resc
     */
    public void save() {
        MenuResc resc = getModel(MenuResc.class);

        menuRescService.modifyModel(resc.set(MenuResc.UPDATE_TIME, DateUtils.getCurrentTime()));
        redirect("/admin/menuresc");
    }

    /**
     * 菜单树
     */
    public void getMenuTree() {
        List<MenuResc> rescs = menuRescService.getMenuRescList();

        StringBuilder sb = new StringBuilder();
        sb.append("[");

        for (MenuResc resc : rescs) {
            if (resc.getStr(MenuResc.TYPE).equals("0")) {
                sb.append("{\"id\":");
                sb.append(resc.getInt(MenuResc.ID));
                sb.append(",\"pId\":");
                sb.append(resc.getInt(MenuResc.PID));
                sb.append(",\"name\":\"");
                sb.append(resc.getStr(MenuResc.NAME));
                sb.append("\"");
                sb.append(",\"open\":true");
                sb.append("}");
                sb.append(",");
            }
        }

        sb.deleteCharAt(sb.length() - 1);
        sb.append("]");
        renderText(sb.toString());
    }
}
